<?php

namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\config\model\ConfigStore;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerContact;
use app\common\order\logic\IncomeLogic;
use app\common\order\model\OrderProduct;
use app\common\order\model\OrderIncome;
use app\common\order\model\OrderSettle;
use app\common\order\validate\OrderBomValidate;
use app\common\order\validate\OrderIncomeValidate;
use app\common\order\validate\OrderProductValidate;
use app\common\order\validate\OrderValidate;
use app\common\order\validate\OrderVipValidate;
use app\common\system\logic\UserDepartmentLogic;
use app\common\system\logic\UserLogic;
use app\common\system\model\OperateLog;
use PhpOffice\PhpSpreadsheet\Worksheet\Row;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\Exception;
use util\Format;

class Order extends Api
{
    public function index()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $where = [];
        $userLogic = new UserLogic();
        $authStoreIds = $userLogic->getStoreAuth($user['id']);
        if ($user['user_type'] != 2) {
            $where[] = ['user_id', '=', $user['id']];
        } else {
            // 存在门店权限使用门店权限，否则使用部门权限
            if (empty($authStoreIds)) {
                $staffIds = $userLogic->getDptUserIds($user['id']);
                $where[] = ['user_id', 'in', $staffIds];
            }
        }
        if (!empty($post['department_id'])) {
            $dptLogic = new UserDepartmentLogic();
            $staffIds = $dptLogic->getDptUserIds($post['department_id']);
            $where[] = ['user_id', 'in', $staffIds];
        }

        if (!empty($post['user_id']))
            $where[] = ['user_id', 'in', $post['user_id']];

        if (!empty($post['status']))
            $where[] = ['status', '=', $post['status']];

        list($cfg) = Format::pagination($post);
        $model = new \app\common\order\model\Order();
        $model = $model->where($where);
        if ($user['user_type'] == 2 && !empty($authStoreIds)) {
            $model = $model->whereIn('id', function ($query) use ($authStoreIds) {
                $query->table('tk_order_bom')->where('store_id', 'in', $authStoreIds)->field('order_id');
            });
        }

        if (!empty($post['event_date_range']) || !empty($post['keyword'])) {
            $hasWhere = [];
            if (!empty($eventDateRange)) {
                $eventDateRange = Format::dateRange($post['event_date_range']);
                $hasWhere[] = ['event_date', 'between', $eventDateRange];
            }

            if (!empty($post['keyword']))  {
                $hasWhere[] = ['order_no|name|phone|urgent_phone|urgent_name', 'like', '%' . $post['keyword'] . '%'];
            }
            $model = $model->whereIn('id', function ($query) use ($hasWhere) {
                $query->table('tk_order_vip')->where($hasWhere)->field('order_id');
            });
        }



        if (!empty($post['store_id']) || !empty($post['sign_date_range']) || !empty($post['brand_id'])) {
            $hasWhere = [];
            if (!empty($post['brand_id'])) {
                $storeIds = ConfigStore::where('company_id', $post['brand_id'])->column('id');
                $hasWhere[] = ['store_id', 'in', $storeIds];
            }

            if (!empty($post['store_id'])) {
                $hasWhere[] = ['store_id', 'in', $post['store_id']];
            }

            if (!empty($post['sign_date_range'])) {
                $signDateRange = Format::dateRange($post['sign_date_range']);
                $hasWhere[] = ['sign_date', 'between', $signDateRange];
            }

            $model->whereIn('id', function ($query) use ($hasWhere) {
                $query->table('tk_order_bom')->where($hasWhere)->field('order_id');
            });
        }

        if (!empty($post['source_id'])) {
            $hasWhere = [];
            $hasWhere[] = ['source_id', 'in', $post['source_id']];
            $model = $model->whereIn('member_id', function ($query) use ($hasWhere) {
                $query->table('tk_member')->where($hasWhere)->where('delete_time', 0)->field('id');
            });
        }

        if (empty($post['is_export'])) {
            // 查询
            $pg = $model->order('id desc')->paginate($cfg);
            $rows = $pg->getCollection();
            foreach ($rows as $row) {
                $row->append(['source', 'user', 'vip', 'bom']);
            }

            // 返回接口数据
            $result['list'] = $rows;
            $result['pagination'] = Format::pgResult($pg);

            return success($result, '获取数据成功');
        } else {

            // 审核状态	订单类型 订单性质 所属公司 渠道来源	合同模式 合同编号	签单销售	签约日期	预产期	姓名	电话	酒店名称	宴会厅	创建时间	
            $header = [
                'source' => '渠道来源',
            ];

            $rows = $model->order('id desc')->select();
            $expData = [];
            foreach ($rows as $row) {
                $attrs = ['user', 'store'];
                $row->append($attrs);
                $data = [];

                $expData[] = $data;
            }

            // print_r($expData);
            $fileName = '【订单】' . date('YmdHis');
            $url = \app\common\third\Excel::exportExcel($expData, $header, $fileName);
            return success(['url' => $url], '导出成功');
        }
    }

    public function export()
    {
        $post = $this->request->post();

        // brand_id
        if (empty($post['brand_id'])) {
            return error([], '请选择品牌');
        }

        // 渠道来源
        $user = $this->request->user;
        $where = [];
        $userLogic = new UserLogic();
        $authStoreIds = $userLogic->getStoreAuth($user['id']);
        if ($user['user_type'] != 2) {
            $where[] = ['user_id', '=', $user['id']];
        } else {
            // 存在门店权限使用门店权限，否则使用部门权限
            if (empty($authStoreIds)) {
                $staffIds = $userLogic->getDptUserIds($user['id']);
                $where[] = ['user_id', 'in', $staffIds];
            }
        }

        
        if (!empty($post['department_id'])) {
            $dptLogic = new UserDepartmentLogic();
            $staffIds = $dptLogic->getDptUserIds($post['department_id']);
            $where[] = ['user_id', 'in', $staffIds];
        }

        if (!empty($post['user_id'])) $where[] = ['user_id', 'in', $post['user_id']];
        if (!empty($post['status'])) $where[] = ['status', '=', $post['status']];

        $model = new \app\common\order\model\Order();
        $model = $model->where($where);

        if ($user['user_type'] == 2 && !empty($authStoreIds)) {
            $model = $model->whereIn('id', function ($query) use ($authStoreIds) {
                $query->table('tk_order_bom')->where('store_id', 'in', $authStoreIds)->field('order_id');
            });
        }

        if (!empty($post['event_date_range']) || !empty($post['keyword'])) {
            $eventDateRange = Format::dateRange($post['event_date_range']);
            $hasWhere = [];
            if (!empty($eventDateRange)) $hasWhere[] = ['event_date', 'between', $eventDateRange];
            if (!empty($post['keyword'])) $hasWhere[] = ['order_no|name|phone|urgent_phone|urgent_name', 'like', '%' . $post['keyword'] . '%'];
            $model = $model->whereIn('id', function ($query) use ($hasWhere) {
                $query->table('tk_order_vip')->where($hasWhere)->field('order_id');
            });
        }

        $hasWhere = [];
        $storeIds = ConfigStore::where('company_id', $post['brand_id'])->column('id');
        $hasWhere[] = ['store_id', 'in', $storeIds];

        if (!empty($post['store_id']) || !empty($post['sign_date_range']) || !empty($authStoreIds)) {

            if (!empty($post['store_id'])) {
                $hasWhere[] = ['store_id', 'in', $post['store_id']];
            }

            if (!empty($post['sign_date_range'])) {
                $signDateRange = Format::dateRange($post['sign_date_range']);
                $hasWhere[] = ['sign_date', 'between', $signDateRange];
            }

            if (!empty($authStoreIds)) $hasWhere[] = ['store_id', 'in', $authStoreIds];
        }
        $model->whereIn('id', function ($query) use ($hasWhere) {
            $query->table('tk_order_bom')->where($hasWhere)->field('order_id');
        });

        if (!empty($post['source_id'])) {
            $hasWhere = [];
            $hasWhere[] = ['source_id', 'in', $post['source_id']];
            $model->whereIn('member_id', function ($query) use ($hasWhere) {
                $query->table('tk_member')->where($hasWhere)->field('id');
            });
        }


        // 日期 渠道 联系方式 是否有效客资 是否到店 预约门店 跟踪销售 出单日期 出单金额
        $header = [
            'create_time' => '客资创建日期',
            'source' => '   渠道',
            'contact' => '联系方式',
            'visit_status' => '是否有效客资',
            'creator' => '客服跟进人',
            'is_visit_store' => '是否到店',
            'store' => '预约门店',
            'invite_time' => '预约时间',
            'sales' => '跟踪销售',
            'sign_date' => '出单日期',
            'order_amount' => '出单金额',
            'first_visit_time' => '一次到店日期',
            'first_visit_remark' => '一次到店备注',
            'second_visit_time' => '二次到店日期',
            'second_visit_remark' => '二次到店备注',
            'third_visit_time' => '三次到店日期',
            'third_visit_remark' => '三次到店备注'
        ];

        $rows = $model->order('id desc')->select();
        $expData = [];
        foreach ($rows as $row) {
            $row->append(['customer', 'invite', 'invites', 'user', 'bom']);
            $data = [];

            // 客资信息
            $customer = $row->customer;
            $data['create_time'] = $customer['create_time'];
            // 客资信息
            $data['source'] = $customer['source']['title'];
            // 分配信息
            $data['contact'] = $customer['contact']['contact'];
            $data['visit_status'] = $customer['visit_status']['title'];
            // 客服跟进人
            $data['creator'] = $customer['creator']['realname'];

            // 到店信息
            $invite = $row->invite;
            $data['is_visit_store'] = $invite['status_text'];
            $data['store'] = $invite['store']['title'];
            $data['invite_time'] = $invite['invite_time'];

            // 订单信息
            $bom = $row->bom;
            $data['sales'] = $bom['user']['realname'];
            $data['sign_date'] = $bom['sign_date'];
            $data['order_amount'] = $bom['totals'];

          

            // 一次到店信息
            $invites = $row->invites;
            $data['first_visit_time'] = $invites['first_visit']['visit_time'];
            $data['first_visit_remark'] = $invites['first_visit']['remark'];

            // 二次到店信息
            $data['second_visit_time'] = $invites['second_visit']['visit_time'];
            $data['second_visit_remark'] = $invites['second_visit']['remark'];

            // 三次到店信息
            $data['third_visit_time'] = $invites['third_visit']['visit_time'];
            $data['third_visit_remark'] = $invites['third_visit']['remark'];

            $expData[] = $data;
        }

        // print_r($expData);

        $fileName = '【订单】' . date('YmdHis');
        $url = \app\common\third\Excel::exportExcel($expData, $header, $fileName);
        return success(['url' => $url], '导出成功');
    }

    // 订单详情
    public function detail()
    {
        $post = $this->request->post();
        if (empty($post['id']))
            return error([], "参数错误");
        $result = [];

        $orderModel = new \app\common\order\model\Order();
        $order = $orderModel->where('id', $post['id'])->find();
        if (empty($order))
            return error([], "订单不存在");

        // 订单基本信息
        $order->append(['source', 'user']);
        $result['order'] = $order;

        // 客资信息
        $customerModel = new Customer();
        $fields = "id,fullname,create_id,source_id";
        try {
            $customer = $customerModel->where('id', $order['member_id'])->field($fields)->find();
            $customer->append(['creator', 'source']);
            $result['customer'] = $customer;
        } catch (DataNotFoundException $e) {
            $result['customer'] = [
                'id' => '',
                'fullname' => '',
                'creator' => [
                    'id' => '',
                    'realname' => '',
                ],
                'source' => [
                    'id' => '',
                    'title' => ''
                ]
            ];
        }

        // 获取跟进人信息
        if ($order['allocate_id'] > 0) {
            $allocateModel = new CustomerAllocate();
            $allocate = $allocateModel::withTrashed()->where('id', $order['allocate_id'])->field('id,member_id,user_id,delete_time')->find();
            // $allocate->append(['user']);
            if ($allocate['delete_time'] > 0) {
                $allocate = $allocateModel->where('member_id', $order['member_id'])->where('user_id', $allocate['user_id'])->field('id,member_id,user_id,delete_time')->find();
            }
            $allocate->append(['user']);
            $result['allocate'] = $allocate;

            // 获取联系方式
            $contactModel = new CustomerContact();
            $contactList = $contactModel->where('member_id', $order['member_id'])->select();
            foreach ($contactList as $row) {
                $row->append(['role_type', 'tag']);
            }
            $result['contactList'] = $contactList;
        } else {
            $result['allocate'] = [
                'id' => '',
                'user' => [
                    'id' => '',
                    'realname' => ''
                ]
            ];
            $result['contactList'] = [];
        }

        // 获取vip信息
        $vipModel = new \app\common\order\model\OrderVip();
        $vip = $vipModel->where('order_id', $order['id'])->hidden(['create_time', 'update_time', 'delete_time'])->find();
        $result['vip'] = $vip;

        // 获取bom信息
        $bomModel = new \app\common\order\model\OrderBom();
        $bom = $bomModel->where('order_id', $order['id'])->hidden(['create_time', 'update_time', 'delete_time'])->find();
        $bom->append(['store', 'package']);
        $result['bom'] = $bom;

        // 付款简介
        return success($result);
    }

    // 创建订单
    public function create()
    {
        $post = $this->request->post();

        if (!isset($post['order'])) {
            return error([], "缺少order参数");
        }

        if (!isset($post['vip'])) {
            return error([], "缺少vip参数");
        }

        if (!isset($post['bom'])) {
            return error([], "缺少bom参数");
        }

        if (!isset($post['income'])) {
            return error([], "缺少income参数");
        }

        $user = $this->request->user;

        $orderValidate = new OrderValidate();
        if (!$orderValidate->check($post['order'])) {
            return error([], $orderValidate->getError());
        }
        $post['order']['user_id'] = $user['id'];
        // order_no, 根据时间生成唯一订单号
        $orderNo = date('YmdHis') . rand(10000, 9999);
        $post['order']['order_no'] = $orderNo;
        $model = new \app\common\order\model\Order();
        $model->startTrans();

        try {
            $model->save($post['order']);
        } catch (Exception $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderId = $model->id;
        // 生成vip订单
        $vipValidate = new OrderVipValidate();
        if ($post['vip']['brand_id'] == 1 || $post['vip']['brand_id'] == 2) {
            // 月子中心的验证规则
            $scene = 'hotel';
        } else {
            // 服务的验证规则
            $scene = 'service';
        }
        if (!$vipValidate->scene($scene)->check($post['vip'])) {
            $model->rollback();
            return error([], $vipValidate->getError());
        }
        $post['vip']['order_id'] = $orderId;
        $post['vip']['order_no'] = $orderNo;
        $vipModel = new \app\common\order\model\OrderVip();
        try {
            $vipModel->save($post['vip']);
        } catch (Exception $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 生成bom订单
        $bomValidate = new OrderBomValidate();
        if (!$bomValidate->check($post['bom'])) {
            $model->rollback();
            return error([], $bomValidate->getError());
        }
        $post['bom']['user_id'] = $user['id'];
        $post['bom']['order_id'] = $orderId;
        $post['bom']['order_no'] = $orderNo;
        $post['bom']['member_id'] = $post['order']['member_id'];
        $bomModel = new \app\common\order\model\OrderBom();
        try {
            $bomModel->save($post['bom']);
        } catch (Exception $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 创建收款记录
        $incomeValidate = new OrderIncomeValidate();
        if (!$incomeValidate->check($post['income'])) {
            $model->rollback();
            return error([], $incomeValidate->getError());
        }
        $post['income']['order_id'] = $orderId;
        $post['income']['order_no'] = $orderNo;
        $post['income']['user_id'] = $user['id'];
        $incomeModel = new OrderIncome();
        try {
            $incomeModel->save($post['income']);
        } catch (Exception $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }


        $model->commit();
        return success([], '创建订单成功');
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $orderValidate = new OrderValidate();
        if (!$orderValidate->check($post)) {
            return error([], $orderValidate->getError());
        }

        $model = new \app\common\order\model\Order();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row))
            return error([], '数据已不存在');

        $model->startTrans();
        try {
            // $post['user_id'] = $user['id'];
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = \app\common\order\model\Order::class;
            OperateLog::write($user['id'], $post['id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }

    // 更新bom订单信息
    public function updateBom()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $bomValidate = new OrderBomValidate();
        if (!$bomValidate->check($post)) {
            return error([], $bomValidate->getError());
        }

        $model = new \app\common\order\model\OrderBom();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row))
            return error([], '数据已不存在');

        if ($row['order_id'] != $post['order_id'])
            return error([], '数据异常');

        $model->startTrans();
        try {
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = \app\common\order\model\OrderBom::class;
            OperateLog::write($user['id'], $post['id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }

    // 更新vip订单信息
    public function updateVip()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $vipValidate = new OrderVipValidate();
        if (!$vipValidate->check($post)) {
            return error([], $vipValidate->getError());
        }

        $model = new \app\common\order\model\OrderVip();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row))
            return error([], '数据已不存在');

        if ($row['order_id'] != $post['order_id'])
            return error([], '数据异常');

        $model->startTrans();
        try {
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = \app\common\order\model\OrderVip::class;
            OperateLog::write($user['id'], $post['id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }

    public function doRefund()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        if (empty($post['id']))
            return error([], "参数错误");

        $model = new \app\common\order\model\Order();
        $row = $model->field('id,refund_status')->where('id', $post['id'])->find();
        if (empty($row))
            return error([], '数据已不存在');

        $model->startTrans();
        try {
            $origin = $row->getData();
            $post['refund_status'] = 1;
            $row->save($post);

            $changed = $row->getData();
            $modelName = \app\common\order\model\Order::class;
            OperateLog::write($user['id'], $post['id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '退单成功');
    }
}
